#!/bin/sh
################################################
# this script is only for CentOS 6.X
# e_mail:434631143@qq.com
# author: wss
# link:http://git.oschina.net/wss/centos6_optimization
# version:20170110 v3.0
################################################

#调用function脚本
. /etc/init.d/functions

#临时设置LANG
export LANG=zh_CN.UTF-8

#检查系统是否是CentOS 6.X
REL=`awk -F '[. ]' '{print $1,$3}' /etc/redhat-release`
if [ "$REL" != "CentOS 6" ];then
 echo -e "\033[31m\n对不起,这个脚本只适合CentOS 6.X系统\n\033[0m"
 exit 1
fi

#检查用户是否为root用户
if [ $(id -u) != "0" ];then
 echo -e "\033[31m\n对不起,必须以root用户身份运行此脚本\n\033[0m"
 exit 1
fi

#定义一个检查是否执行成功的函数
check_ok(){
  if [ $? -eq 0 ];then
     echo ""
  else
     action "脚本异常中断,请检查错误" /bin/false
     exit $1
  fi
}

#时间
DATE=`date +"%Y-%m-%d %H:%M:%S"`
#ip地址
IPADDR=`ifconfig eth0 | grep 'inet addr' | cut -d ':' -f2 | cut -d ' ' -f1`
#主机名
HOSTNAME=`hostname`
#用户
USER=`whoami`
#磁盘使用率
DISK_SDA=`df -h |grep -w "/" |awk '{print $5}'`
#cpu负载
cpu_uptime=`cat /proc/loadavg|awk '{print $1,$2,$3}'`


#解决使用退格键时出现^H
\cp /etc/profile /etc/profile_$(date +%F)
erase=`grep -wx "stty erase ^H" /etc/profile |wc -l`
if [ $erase -lt 1 ];then
 cat >> /etc/profile << EOF
#解决使用退格键时出现^H
stty erase ^H
EOF
 source /etc/profile
fi

#开启vi彩色
yum -y install vim-enhanced
export TERM=xterm-color
echo "syntax on" >>~/.vimrc
echo "hi  Comment  ctermfg=6" >>~/.vimrc
echo "syntax on" >>/etc/vimrc
echo "hi  Comment  ctermfg=6" >>/etc/vimrc
echo "alias vi='vim'" >>~/.bashrc
echo "alias vi='vim'" >>/etc/bashrc

#定时清理邮件服务临时目录垃圾文件
mkdir -p /scripts
echo "find /var/spool/postfix/maildrop/ -type f|xargs rm -f" >/scripts/del_maildrop.sh
echo "#定时清理邮件服务临时目录垃圾文件">>/var/spool/cron/root
echo "00 00 * * * /bin/sh /scripts/del_maildrop.sh >/dev/null 2>&1">>/var/spool/cron/root



#禁用ipv6,重启系统生效
DisableIPv6(){
ifconfig | grep -i inet6 
lsmod | grep -i ipv6

#关闭ipv6相关模块
cat > /etc/modprobe.d/ipv6.conf << EOF
#关闭ipv6相关模块
alias net-pf-10 off
#重启网卡时会报错,暂时注释掉
#alias ipv6 off
options ipv6 disable=1
EOF

#禁用ipv6的网络
echo "NETWORKING_IPV6=no" >> /etc/sysconfig/network

#禁用ipv6的iptables
/etc/init.d/ip6tables stop
chkconfig ip6tables off
}

# 去除系统及内核版本登录前的屏幕显示
HideVersion(){
 [ -f "/etc/redhat-release" ]  && \cp /etc/redhat-release /etc/sysconfig/redhat-release.$(date +%F) && >/etc/redhat-release
 [ -f "/etc/issue" ] && \cp /etc/issue /etc/issue.$(date +%F) && >/etc/issue
 [ -f "/etc/issue.net" ] && \cp /etc/issue.net /etc/issue.net.$(date +%F) && > /etc/issue.net
}

#锁定关键文件系统
LockCriticalFile() {
 chattr +i /etc/passwd
 chattr +i /etc/inittab
 chattr +i /etc/group
 chattr +i /etc/shadow
 chattr +i /etc/gshadow
}

#安装必要的系统包组及工具
initTools(){
echo -e "\033[32m\n============安装必要的系统包组及工具=============\n\033[0m"
 #安装必要的系统包组
 yum groupinstall "Base" "Compatibility libraries" "debugging Tools" "Development tools" -y
 #安装必要的系统工具
 yum install tree nmap sysstat lrzsz dos2unix telnet ntpdate nload -y
 check_ok
echo -e "\033[32m\n=================================================\n\033[0m"
}


#配置阿里云YUM源
configYum(){
echo -e "\033[32m\n===============配置阿里云YUM源==================\n\033[0m"
 ping -c 3 mirrors.aliyun.com &>/dev/null 
 if [ $? -ne 0 ];then
 echo "无法连接网络..."
 exit $?
 else
 #安装aliyun源
 mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.$(date +%F)
 wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
 #安装aluyun-epel源
 mv /etc/yum.repos.d/epel.repo /etc/yum.repos.d/epel.repo.$(date +%F)
 mv /etc/yum.repos.d/epel-testing.repo /etc/yum.repos.d/epel-testing.repo.$(date +%F)
 wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
 #清空yum缓存
 yum clean all
 #建立yum缓存
 yum makecache
 #导入签名KEY到RPM
 rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY*
 check_ok
action "配置阿里云YUM源完成" /bin/true
echo -e "\033[32m\n=================================================\n\033[0m"
 sleep 2
 fi
}
 
#更改字符集为zh_CN.UTF-8
initI18n(){
echo -e "\033[32m\n============更改字符集为zh_CN.UTF-8==============\n\033[0m"
 \cp /etc/sysconfig/i18n /etc/sysconfig/i18n.$(date +%F)
 echo "LANG="zh_CN.UTF-8"" >/etc/sysconfig/i18n
 source /etc/sysconfig/i18n
 echo '#cat /etc/sysconfig/i18n'
 grep LANG /etc/sysconfig/i18n
 check_ok
action "更改字符集为zh_CN.UTF-8完成" /bin/true
echo -e "\033[32m\n=================================================\n\033[0m"
 sleep 2
}

#禁用SELINUX并关闭防火墙
initFirewall(){
echo -e "\033[32m\n============禁用SELINUX并关闭防火墙=============="
 \cp /etc/selinux/config /etc/selinux/config.$(date +%F)
 /etc/init.d/iptables stop
 sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
 setenforce 0
 /etc/init.d/iptables status
 grep SELINUX=disabled /etc/selinux/config 
 check_ok 
action "禁用selinux并关闭防火墙完成" /bin/true
echo -e "\033[32m\n=================================================\n\033[0m"
 sleep 2
}

#简开机自启动
initService(){
echo -e "\033[32m\n===============精简开机自启动====================\n\033[0m"
 export LANG="en_US.UTF-8"
 for services in `chkconfig --list|grep 3:on|awk '{print $1}'|grep -Ev "crond|network|rsyslog|sshd|sysstat"`;
 do 
	chkconfig $services off;
 done
 check_ok
 export LANG="zh_CN.UTF-8"
action "精简开机自启动完成" /bin/true
echo -e "\033[32m\n=================================================\n\033[0m"
 sleep 2
}

#ssh安全优化
initSsh(){
echo -e "\033[32m\n========修改ssh默认端口并禁用root远程登录========\n\033[0m"
 \cp /etc/ssh/sshd_config /etc/ssh/sshd_config.$(date +%F)
 sed -i 's/#Port 22/Port 52113/g' /etc/ssh/sshd_config
 sed -i 's/#PermitEmptyPasswords no/PermitEmptyPasswords no/g' /etc/ssh/sshd_config
 sed -i 's/#PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config
 sed -i 's/#UseDNS yes/UseDNS no/g' /etc/ssh/sshd_config
 sed -i 's/GSSAPIAuthentication yes/GSSAPIAuthentication no/g' /etc/ssh/sshd_config
 echo '+------------修改内容如下------------+'
 echo 'Port 52113'
 echo 'PermitEmptyPasswords no'
 echo 'PermitRootLogin no'
 echo 'UseDNS no'
 echo 'GSSAPIAuthentication no'
 echo '+------------------------------------+'
 /etc/init.d/sshd reload
 check_ok
 action "修改ssh默认参数完成" /bin/true
echo -e "\033[32m\n=================================================\n\033[0m"
 sleep 2
}

#配置时间同步
syncSysTime(){
echo -e "\033[32m\n================配置时间同步=====================\n\033[0m"
 \cp /var/spool/cron/root /var/spool/cron/root.$(date +%F) 2>/dev/null
 NTPDATE=`grep ntpdate /var/spool/cron/root 2>/dev/null |wc -l`
 if [ $NTPDATE -eq 0 ];then
 echo "#时间同步" >>/var/spool/cron/root
 echo "*/5 * * * * /usr/sbin/ntpdate time.windows.com >/dev/null 2>&1" >> /var/spool/cron/root
 fi
 echo '#crontab -l' 
 crontab -l|grep ntpdate
 check_ok
action "配置时间同步完成" /bin/true
echo -e "\033[32m\n=================================================\n\033[0m"
 sleep 2
}

#新建一个用户并将其加入visudo
addUser(){
echo -e "\033[32m\n===================新建用户======================\n\033[0m"
#新建用户
while true
do 
 read -p "请输入新用户名:" name
 NAME=`awk -F':' '{print $1}' /etc/passwd|grep -wx $name 2>/dev/null|wc -l`
 if [ ${#name} -eq 0 ];then
 echo "用户名不能为空，请重新输入。"
 continue
 elif [ $NAME -eq 1 ];then
 echo "用户名已存在，请重新输入。"
 continue
 fi
useradd $name 2>/dev/null
if [ $? -ne 0 ];then
 echo "输入的用户名不合法，请重新输入。"
 continue
else
 break
fi
done

#设置新建用户的密码
while true
do
 read -p "为 $name 创建一个密码:" pass1
 if [ ${#pass1} -eq 0 ];then
 echo "密码不能为空，请重新输入。"
 continue
 fi
 read -p "请再次输入密码:" pass2
 if [ "$pass1" != "$pass2" ];then
 echo "两次密码输入不一致，请重新输入。"
 continue
 fi
echo "$pass2" |passwd --stdin $name
break
done
sleep 1

#设置新建用户的visudo
\cp /etc/sudoers /etc/sudoers.$(date +%F)
SUDO=`grep -w "$name" /etc/sudoers |wc -l`
if [ $SUDO -eq 0 ];then
 echo "$name ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
 echo '#tail -1 /etc/sudoers'
 grep -w "$name" /etc/sudoers
 sleep 1
fi
check_ok
action "新建用户$name并将其加入visudo完成" /bin/true
echo -e "\033[32m\n=================================================\n\033[0m"
sleep 2
}



#加大文件描述符(limits.conf)
initLimits(){
echo -e "\033[32m\n===============加大文件描述符====================\n\033[0m"
 LIMIT=`grep nofile /etc/security/limits.conf |grep -v "^#"|wc -l`
 if [ $LIMIT -eq 0 ];then
 \cp /etc/security/limits.conf /etc/security/limits.conf.$(date +%F)
 ulimit -HSn 65535
 echo "ulimit -SHn 65535" >> /etc/rc.local
cat >> /etc/security/limits.conf << EOF
*           soft   nofile       65535
*           hard   nofile       65535
EOF
 fi
 check_ok
action "配置文件描述符为65535" /bin/true
echo -e "\033[32m\n=================================================\n\033[0m"
sleep 2
}


#优化内核参数
initSysctl(){
echo -e "\033[32m\n================优化内核参数=====================\n\033[0m"
SYSCTL=`grep "net.ipv4.tcp" /etc/sysctl.conf |wc -l`
if [ $SYSCTL -lt 10 ];then
\cp /etc/sysctl.conf /etc/sysctl.conf.$(date +%F)
cat >>/etc/sysctl.conf<<EOF
#by sun in 20131001
net.ipv4.tcp_fin_timeout = 2
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.ip_local_port_range = 4000 65000
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.route.gc_timeout = 100
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.core.somaxconn = 16384
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_max_orphans = 16384
#以下参数是对iptables防火墙的优化，防火墙不开会有提示，可以忽略不理。
net.netfilter.nf_conntrack_max = 25000000
net.netfilter.nf_conntrack_tcp_timeout_established = 180
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 120
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 120
EOF
fi
 \cp /etc/rc.local /etc/rc.local.$(date +%F) 
 modprobe nf_conntrack
 echo "modprobe nf_conntrack">> /etc/rc.local
 modprobe bridge
 echo "modprobe bridge">> /etc/rc.local
 sysctl -p 
action "内核调优完成" /bin/true
echo -e "\033[32m\n=================================================\n\033[0m"
 sleep 2
}

#menu2
menu2(){
while true
do
clear
cat << EOF
----------------------------------------
|****请选择优化内容:****|
----------------------------------------
1.新建一个用户并将其加入visudo
2.配置阿里云YUM源
3.配置中文字符集
4.禁用SELINUX并关闭防火墙
5.精简开机自启动
6.修改ssh默认端口及禁用root远程登录
7.设置时间同步
8.加大文件描述符
9.内核参数调优
0.返回上一级菜单
EOF
read -p "Please enter your Choice[0-9]: " input2
case "$input2" in
 0)
 clear
 break 
 ;;
 1)
 addUser
 ;;
 2)
 configYum
 ;;
 3)
 initI18n
 ;;
 4)
 initFirewall
 ;;
 5)
 initService
 ;;
 6)
 initSsh
 ;;
 7)
 syncSysTime
 ;;
 8)
 initLimits
 ;;
 9)
 initSysctl
 ;;
 *) echo "----------------------------------"
 echo "| Warning!!! |"
 echo "| Please Enter Right Choice! |"
 echo "----------------------------------"
 for i in `seq -w 3 -1 1`
 do 
 echo -ne "\b\b$i";
 sleep 1;
 done
 clear
esac
done
}

#initTools

#menu
while true
do
clear
echo "========================================"
echo ' CentOS 6.X优化 ' 
echo "========================================"
cat << EOF

---------------系统信息-----------------
| 时间:$DATE
| 主机名:$HOSTNAME
| 当前用户:$USER
| IP地址:$IPADDR
| 磁盘使用率:$DISK_SDA
| CPU负载:$cpu_uptime
----------------------------------------
|****请选择优化类型:****|
----------------------------------------
1.一键优化
2.自定义优化
3.退出
EOF
#choice
read -p "Please enter your choice[1-3]: " input1


case "$input1" in
1) 
 addUser
 configYum
 initI18n
 initFirewall
 initService
 initSsh
 syncSysTime
 initLimits
 initSysctl
 ;;
 
2)
 menu2
 ;;

3) 
 clear 
 break
 ;;

*) 
 echo "----------------------------------"
 echo "| Warning!!! |"
 echo "| Please Enter Right Choice! |"
 echo "----------------------------------"
 for i in `seq -w 3 -1 1`
 do
 echo -ne "\b\b$i";
 sleep 1;
 done
 clear
esac 
done
